#include "StdAfx.h"
#include "Card.h"
#include "GResLoad.h"

GCard gCard;
GCard::GCard(void)
{
}
GCard& GCard::Inst()
{
	return gCard;
}
GCard::~GCard(void)
{
}
DWORD GCard::LoadResource(const char* szPath)
{
	TiXmlDocument doc;  
	if (!doc.LoadFile(szPath))
	{  	
		assert(0);
		return 0;
	}

	int texture, number;
	TiXmlElement* DlgMgrElem = doc.RootElement();
	map<tstring, tstring> mapAtt;
	map<tstring, tstring>::iterator iter;
	pair<map<tstring, tstring>::iterator, bool> ret;
	for(const TiXmlAttribute *pAtt  = DlgMgrElem->FirstAttribute(); pAtt!=NULL; pAtt = pAtt->Next())
	{		
		ret = mapAtt.insert(make_pair(conversion::UTF8ToUnicode(pAtt->Name()), conversion::UTF8ToUnicode(pAtt->Value())));
		if (ret.second == false) assert(0);
	}
	iter = mapAtt.find(_T("width"));
	if (iter == mapAtt.end()) assert(0);
	m_nWidth = wcstod(iter->second.c_str(), NULL);

	iter = mapAtt.find(_T("height"));
	if (iter == mapAtt.end()) assert(0);
	m_nHeigth = wcstod(iter->second.c_str(), NULL);

	for (TiXmlElement* DlgElem = DlgMgrElem->FirstChildElement(); DlgElem!=NULL; DlgElem = DlgElem->NextSiblingElement())
	{
		mapAtt.clear();
		for(const TiXmlAttribute *pAtt  = DlgElem->FirstAttribute(); pAtt!=NULL; pAtt = pAtt->Next())
		{
			ret = mapAtt.insert(make_pair(conversion::UTF8ToUnicode(pAtt->Name()), conversion::UTF8ToUnicode(pAtt->Value())));
			if (ret.second == false) assert(0);
		}

		iter = mapAtt.find(_T("id"));
		if (iter == mapAtt.end()) assert(0);
		number = wcstod(iter->second.c_str(), NULL);

		iter = mapAtt.find(_T("path"));
		if (iter == mapAtt.end()) assert(0);
		texture = GImageLoad::LoadTextureFromFile(iter->second.c_str());

		m_mapCard.insert(make_pair(number, texture));
	}
	return 0;
}

void GCard::Draw(int number, int x, int y)
{
	map<int, int>::iterator iter;
	iter = m_mapCard.find(number);
	if (iter == m_mapCard.end()) assert(0);
	
	glBindTexture(GL_TEXTURE_2D, iter->second);
	glBegin(GL_QUADS);
	glTexCoord2f( 0, 0);glVertex2f(x, y);  
	glTexCoord2f( 1, 0);glVertex2f(x+m_nWidth, y);
	glTexCoord2f( 1, 1);glVertex2f(x+m_nWidth, y+m_nHeigth);
	glTexCoord2f( 0, 1);glVertex2f(x, y+m_nHeigth);	
	glEnd();
}
